package com.zy.openchat.core.model.user;

import android.os.Parcel;
import android.os.Parcelable;

import com.ja.openchat.R;
import com.scottyab.aescrypt.AESCrypt;
import com.zy.openchat.App;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.photo.ProfilePhoto;
import com.zy.openchat.util.UrlParse;

import org.apache.commons.lang3.StringUtils;

import java.net.URLEncoder;
import java.util.Map;

public class UserInfo implements Parcelable {
    private volatile static UserInfo g_userInfo;

    public UserInfo() {
    }

    public static UserInfo getUserInfo() {
        if (g_userInfo == null) {
            synchronized (UserInfo.class) {
                if (g_userInfo == null) {
                    g_userInfo = new UserInfo();
                }
            }
        }
        return g_userInfo;
    }

    public long id;
    public String first_name;
    public String last_name;
    public String phone_number;
    public String username;
    public String raw_first_name;
    public String raw_last_name;

    public boolean is_contact;
    public boolean is_mutual_contact;
    public boolean is_verified;
    public UserStatus status;
    public UserType type;

    public String realDisplayName;

    public String getUserStatusLable(){
        if(status!=null){
            return status.getLable();
        }else{
            return "";
        }
    }

    public boolean isDeleteAccount() {
        return type==null?false:"userTypeDeleted".equals(type.type);
    }

    public boolean isOnline(){
        if(id == UserInfo.getUserInfo().id){
            return true;
        }
        if(status==null){
            return false;
        }
        String onlineStyle = status.type;
        if ("userStatusOnline".equals(onlineStyle) || "userStatusRecently".equals(onlineStyle)){
            return true;
        }
//        if("userStatusOffline".equals(onlineStyle)&&status.was_online< TimeUtils.day){
//            return true;
//        }
        return false;
    }

    //displayName对应的拼音
    public String displayName_full_py;

    //显示的名称
    public String displayName() {
        return isDeleteAccount()?App.getInstanse().getString(R.string.already_clean_account):(StringUtils.isEmpty(first_name) ? "" : first_name) + (StringUtils.isEmpty(last_name) ? "" : last_name);
    }

    //获取任意用户显示名称
    public static String userDisplayName(long userId) {
        UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(userId);
        if (user != null) {
            return user.isDeleteAccount()? App.getInstanse().getString(R.string.already_clean_account) :user.displayName();
        }
        return "" + userId;
    }

    public static UserInfo getUserInfo(long userId) {
        UserInfo userInfo = TelegramManager.getTelegramManager().getTgData().contactInfo(userId);
        return userInfo;
    }

    //关键字是否匹配
    public boolean isMatch(String keyword) {
        if (!StringUtils.isEmpty(keyword)) {
            String display = displayName();
            if (!StringUtils.isEmpty(display)) {
                if (display.toUpperCase().contains(keyword.toUpperCase())) {
                    return true;
                }
            }
            if (!StringUtils.isEmpty(displayName_full_py)) {
                if (displayName_full_py.toUpperCase().contains(keyword.toUpperCase())) {
                    return true;
                }
            }
            if (!StringUtils.isEmpty(username)) {
                if (username.toUpperCase().contains(keyword.toUpperCase())) {
                    return true;
                }
            }
        }
        return false;
    }

    //头像
    public ProfilePhoto profile_photo;

    //是否可以通过手机号码搜索到当前用户 - 只对单例有效
    public boolean isFindByPhoneNumber;

    //当前消息未读总数 - 只对单例有效
    public int msgUnreadTotalCount;

    //用户数据目录 - 只对单例有效
    public String data_directory;

    //临时变量 - 只对单例有效，是否密码登录方式
    public boolean isPasswordLoginType;
    public boolean isPasswordRegisterType;

    //个人二维码相关
    public String qrString() {
        String uidString = encryptString("" + id);
        String qr = String.format(Constants.KHostShareAddress + "?uid=%s", uidString);
        Constants.Loge("qr", qr);
        return qr;
    }

    private String encryptString(String text) {
        try {
            return URLEncoder.encode(AESCrypt.encrypt(Constants.AesPassword, text));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String decryptString(String text) {
        try {
            return AESCrypt.decrypt(Constants.AesPassword, text);
        } catch (Exception e) {
            Constants.Loge("qr-decryptString", text + "," + e.getLocalizedMessage());
        }
        return "";
    }

    //解析二维码
    //-1表示无效qrString
    public static long userIdFromQrString(String qrString) {
        try {
            Constants.Loge("qr", qrString);
            Map<String, String> query_pairs = UrlParse.getUrlParams(qrString);
            if (query_pairs != null && query_pairs.size() > 0) {
                String idString = query_pairs.get("uid");
                if (!StringUtils.isEmpty(idString)) {
                    return Long.parseLong(decryptString(idString));
                }
            }
        } catch (Exception e) {
            Constants.Loge("qr", qrString + "," + e.getLocalizedMessage());
        }
        return -1;
    }

    //重置
    public void reset() {
        this.id = 0;
        this.first_name = null;
        this.last_name = null;
        this.phone_number = null;
        this.username = null;
        this.is_contact = false;
        this.is_mutual_contact = false;
        this.is_verified = false;
        this.displayName_full_py = null;
        this.profile_photo = null;
        this.msgUnreadTotalCount = 0;
        this.raw_first_name = null;
        this.raw_last_name = null;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(this.id);
        dest.writeString(this.first_name);
        dest.writeString(this.last_name);
        dest.writeString(this.phone_number);
        dest.writeString(this.username);
        dest.writeByte(this.is_contact ? (byte) 1 : (byte) 0);
        dest.writeByte(this.is_mutual_contact ? (byte) 1 : (byte) 0);
        dest.writeByte(this.is_verified ? (byte) 1 : (byte) 0);
        dest.writeString(this.displayName_full_py);
        dest.writeParcelable(this.profile_photo, flags);
        dest.writeInt(this.msgUnreadTotalCount);
        dest.writeString(this.data_directory);
        dest.writeParcelable(this.status, flags);
        dest.writeParcelable(this.type, flags);
        dest.writeString(this.raw_first_name);
        dest.writeString(this.raw_last_name);
    }

    protected UserInfo(Parcel in) {
        this.id = in.readLong();
        this.first_name = in.readString();
        this.last_name = in.readString();
        this.phone_number = in.readString();
        this.username = in.readString();
        this.is_contact = in.readByte() != 0;
        this.is_mutual_contact = in.readByte() != 0;
        this.is_verified = in.readByte() != 0;
        this.displayName_full_py = in.readString();
        this.profile_photo = in.readParcelable(ProfilePhoto.class.getClassLoader());
        this.msgUnreadTotalCount = in.readInt();
        this.data_directory = in.readString();
        this.status = in.readParcelable(UserStatus.class.getClassLoader());
        this.type = in.readParcelable(UserType.class.getClassLoader());
        this.raw_first_name = in.readString();
        this.raw_last_name = in.readString();
    }

    public static final Creator<UserInfo> CREATOR = new Creator<UserInfo>() {
        @Override
        public UserInfo createFromParcel(Parcel source) {
            return new UserInfo(source);
        }

        @Override
        public UserInfo[] newArray(int size) {
            return new UserInfo[size];
        }
    };

    public boolean isOptAdd() {
        return id == -1;
    }

    public boolean isOptDel() {
        return id == -2;
    }



    public boolean canSendMsg() {
        if (is_contact||id == TelegramManager.TG_USERID_SYSTEM_NOTICE) {//已经是好友的，不受任何影响
            return true;
        }
        if(UserInfo.getUserInfo()!=null&&UserInfo.getUserInfo().id == id){
            return true;
        }
        AppConfigInfo info = AppConfigInfo.getAppConfigInfo();
        if (info != null) {
            if (info.onlyWhiteAddFriend) {
                return false;
            }
            if (info.onlyFriendChat) {//加好友才能聊天
                return is_contact;
            }
        }
        return true;
    }
}